# -*- coding: utf-8 -*-

import json
import requests
import base64
import sys
import os
import time




class XiaolanBrain(object):

    def __init__(self, data):
        
        from XiaolanClientCommandDo import ClientCommandDo
        self.xcc = ClientCommandDo()
        from xiaolanSkillCommandDo import SkillCommandDo
        self.xsc = SkillCommandDo()
        from Log import Log
        self.Log = Log()
        self.data = data
        self.event = {}


    def error_way_return(self):

        """
        技能请求错误返回
        :return:
        """

        return {
            'XiaolanBrainEvent': {
                'Header': {
                    'NameSpace': 'xiaolan.brain.respones.skill.error',
                    'RequestsId': '7679',
                    'RequestsFrom': 'XiaolanBrain',
                    'RequestsAuth': base64.b64decode(self.datebase.GetDate("XiaolanBrainPassword", "XiaolanBrainDate")),
                    'TimeStamp': self.data['ClientEvent']['Header']['TimeStamp']
                },
                'ClientSendData': self.data
            },
            'SkillSendInfo': {},
            'Debug': {
                'Commands': [],
                'TimeStamp': time.time(),
                'Loc': 'GPSstatesError',
                'ErrorMessage': 'TimeOut'
            }
        }

    def GetSendToSkillDataNormal(self, ConversationMainInfo, LogMainInfo):

        """
        获取发送给技能的data
        :param ConversationMainInfo:
        :param LogMainInfo:
        :return:
        """

        return {
            'XiaolanBrainEvent': {
                'Header': {
                    'NameSpace': 'xiaolan.brain.requests.skill',
                    'RequestsId': '7679',
                    'RequestsFrom': 'XiaolanBrain',
                    'RequestsAuth': base64.b64decode(self.datebase.GetDate("XiaolanBrainPassword", "XiaolanBrainDate")),
                    'TimeStamp': self.data['ClientEvent']['Header']['TimeStamp']
                },
                'ClientSendData': self.data
            },
            'SendToSkillInfo': {
                'Text': ConversationMainInfo['Text'],
                'AwakenKeyword': ConversationMainInfo['Keyword'],
                'Intent': ConversationMainInfo['Intent'],
                'WordLexer': ConversationMainInfo['WordLexer'],
                'SkillDate': ConversationMainInfo['SkillDate'],
                'Slots': ConversationMainInfo['Slots']
            },
            'Debug': {
                'Commands': [],
                'TimeStamp': time.time(),
                'Loc': 'GPSstatesError'
            }
        }

    def Run(self):

        """
        主要处理
        :return:
        """

        if self.data['ClientEvent']['Header']['NameSpace'] == 'xiaolan.client.requests.user.skill.need':

            ConversationMainInfo = self.xcc.dataSkillOut()
            LogMainInfo = self.xcc.dataLogOut()
            SkillUrl = self.datebase.GetDate(ConversationMainInfo['Skill'], "xiaolanSkill")

            data = self.GetSendToSkillDataNormal(ConversationMainInfo, LogMainInfo)
            r = requests.post(SkillUrl,
                              data=data)
            json = r.json()

            if json['SkillEvent']['Header']['NameSpace'] != 'skill.respones.error':
                return json.dumps(self.error_way_return())
            else:
                return json.dumps(self.xsc.SkillInfoTurnToServerInfo(json))

        elif self.data['ClientEvent']['Header']['NameSpace'] == 'xiaolan.client.respones.skill.askslots':

            SlotsInfo = self.xcc.dataSlotsOut()
            ConversationMainInfo = self.xcc.dataSkillOut()
            LogMainInfo = self.xcc.dataLogOut()
            SkillUrl = self.datebase.GetDate(ConversationMainInfo['Skill'], "xiaolanSkill")

            data = self.GetSendToSkillDataNormal(ConversationMainInfo, LogMainInfo)
            r = requests.post(SkillUrl,
                              data=data)
            json = r.json()

            if json['SkillEvent']['Header']['NameSpace'] != 'skill.respones.error':
                return json.dumps(self.error_way_return())
            else:
                return json.dumps(self.xsc.SkillInfoTurnToServerInfo(json))


def application(environ, start_response):

        """
        HTTP请求处理函数
        :param environ:
        :param start_response:
        :return:
        """

        method = environ.get('REQUEST_METHOD', 'HEAD')
        if method == "HEAD":
            response_headers = [('Content-Type', 'application/json'),
                                ('Content-Length', str(len("")))]
            start_response('200 OK', response_headers)
            return ""
        else:
            try:
                request_body_size = int(environ.get('CONTENT_LENGTH', 0))
            except(ValueError):
                request_body_size = 0
            request_body = environ['wsgi.input'].read(request_body_size).decode('utf-8')
            print('request_body = %s\n' % request_body)
            if not request_body:
                return ['未获取到请求数据']

            bot = XiaolanBrain(json.loads(request_body))

            body_str = bot.Run()

            body = body_str.encode('utf-8')

            response_headers = [('Content-Type', 'application/json'),
                                ('Content-Length', str(len(body)))]
            status = '200 OK'

            start_response(status, response_headers)

            return [body]



